package com.heima.comment.service.impl;

import com.heima.aliyun.GreenTextScan;
import com.heima.comment.service.TextReviewsService;
import com.heima.common.exception.CustException;
import com.heima.feigns.AdminFeign;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.SensitiveWordUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author huan
 * @serial 每天一百行, 致敬未来的自己
 * @Description
 */
@Service
@Slf4j
public class TextReviewsServiceImpl implements TextReviewsService {

    @Autowired
    AdminFeign adminFeign;
    @Autowired
    private GreenTextScan greenTextScan;

    /**
     * 阿里云文本审核
     *
     * @param content
     * @return
     */
    public String handleTextScan(String content) {
        Map<String, String> map = null;
        try {
            map = greenTextScan.greenTextScan(content);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("阿里云内容敏感词过滤出错 msg ==>{}", e.getMessage());
        }
        String suggestion = map.get("suggestion");
        if ("block".equals(suggestion)) {
            //文本有违规
            String filteredContent = map.get("filteredContent");
            if (filteredContent == null) {
                return content;
            }
        }
        return content;
    }

    /**
     * 基于DFA 检测内容是否包含敏感词
     *
     * @param content
     * @return
     */
    public String handleSensitive(String content) {
        //调用adminFeign远程接口 查询admin模块中敏感词数据
        ResponseResult<List<String>> result = adminFeign.selectAllSensitive();
        if (!result.checkCode()) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR, result.getErrorMessage());
        }
        if (result.getData() == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "查询不到敏感词数据");
        }
        List<String> data = result.getData();
        //将敏感词转化为DFA类型
        SensitiveWordUtil.initMap(data);
        //检测文本信息中的敏感词汇
        Map<String, Integer> resultMap = SensitiveWordUtil.matchWords(content);
        if (resultMap != null && resultMap.size() > 0) {
            Set<String> keys = resultMap.keySet();
            for (String key : keys) {
                content = content.replace(key, "*");
            }
            log.error("检测到敏感词 {}", resultMap);
            return content;
        }
        return content;
    }
}
